#include "file.h"

#include <cstring>

#include <QDateTime>
#include <QDir>

namespace Avd {

File::File(const QString& name, const QString& path,
					 unsigned int size, unsigned int version,  const QString& modDate) :
name(name), path(QDir::cleanPath(path)),
modDate(QDateTime::fromString(modDate,Qt::ISODate)),
size(size), version(version), data(0), temporary(false) { }

File::File(QString& pathName, unsigned int size,
					 unsigned int version) :
size(size), version(version) , data(0), temporary(false) {
	int lastBarPos = pathName.lastIndexOf("/");
	name = pathName.right(pathName.size() - lastBarPos - 1);
	pathName.resize(lastBarPos + 1);
	path = QDir::cleanPath(pathName);
}

File::File(const File& _file) {
	data = 0;
	if(_file.data) {
		data = new char[_file.getSize()];
		memcpy(data, _file.data, _file.getSize());
	}
	name = _file.name;
	path = _file.path;
	modDate = _file.modDate;
	size = _file.size;
	version = _file.version;
	temporary = _file.temporary;
}

File& File::operator=(const File& _file) {
	if(this != &_file) {
		data = 0;
		if(_file.data) {
			data = new char[_file.getSize()];
			memmove(data, _file.data, _file.getSize());
		}
		name = _file.name;
		path = _file.path;
		modDate = _file.modDate;
		size = _file.size;
		version = _file.version;
		temporary = _file.temporary;
	}
	return *this;
}

File::~File() {
//	if(data)
//		delete[] data;
}

QString File::getTempName() const{
	QString tempName(name);
	// name.part.totalParts.version
	tempName.append("." + QString::number(part) +
									"." + QString::number(totalParts) +
									"." + QString::number(version));

	return tempName;
}

QString File::getTempPath() const {
	return QDir::cleanPath(path + "./avd/tmp");
}

QString File::getFullPath() const {
	return QDir::cleanPath(path + "/" + name);
}

QString File::getTempFullPath() const {
	return QDir::cleanPath(path + "/.avd/tmp/" + getTempName());
}

char* File::getData() {
	return data;
}

void File::setData(const char* _data, const unsigned int size) {
	if(data)
		delete[] data;
	data = new char[size];
	memmove(data, _data, size);
}

void File::setTemp(const unsigned int part, const unsigned int totalParts) {
	temporary = true;
	this->part = part;
	this->totalParts = totalParts;
}

}
